<?php


namespace app\api\model;


use app\common\library\WXBizMsgCrypt;
use think\Model;

class CorpModel extends Model
{
    // 表名
    protected $name = 'corp';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    //模板回调验证
    public static function verify($receiveid,$token,$encodingAesKey,$debug='')
    {
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sVerifyEchoStr = isset($_GET['echostr'])?$_GET['echostr']:'';
        $sEchoStr = '';
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        log_print('$sEchoStr');
        log_print($sEchoStr);
        //var_dump($sEchoStr);
        if ($errCode === 0) {
            //log_print($sEchoStr);
            // 验证URL成功
            //echo 'success';
            //die();
            return $sEchoStr;
            //return $sEchoStr;
        } else {
            log_print('回调失败');
            log_print("ERR: " . $errCode.'-rid-'.$receiveid.'-'.$debug);
            return '回调失败'.$debug;
        }
    }

    //刷新 suite_ticket
    public static function DecryptMsgSave($receiveid,$token,$encodingAesKey,$postStr)
    {
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sMsg = '';
        $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $postStr, $sMsg);
        log_print('解密后的数据');
        log_print($sMsg);
        $sMsgArray = Xml2Array($sMsg);
        log_print('解密后转为数组');
        log_print($sMsgArray);
        //print_r($sMsgArray);die();
        if(!empty($sMsgArray['InfoType']) && $sMsgArray['InfoType'] == 'suite_ticket'){
            CorpModel::createOrUp($sMsgArray);
        }
        if(!empty($sMsgArray['InfoType']) && $sMsgArray['InfoType'] == 'reset_permanent_code'){
            $row = CorpModel::where("SuiteId",$sMsgArray['SuiteId'])->find();
            $suite_access_token = WorkModel::get_suite_token($row['SuiteId'],$row['suite_secret'],$row['suite_ticket']);
            WorkModel::get_permanent_code($suite_access_token,$sMsgArray['AuthCode'],$row['SuiteId']);
        }
        if($errCode === 0){
            log_print('解密内容');
            log_print($sMsg);
            return 'success';
        }else{
            log_print('回调失败33333');
            log_print("ERR: " . $errCode);
            return '';
        }
    }

    public static function createOrUp($sMsgArray)
    {
        $row=CorpModel::where('SuiteId',$sMsgArray['SuiteId'])->find();
        if(!empty($row)){
            $row->suite_ticket = $sMsgArray['SuiteTicket'];
            $row->ticket_time = date('Y-m-d H:i:s');
            $row->ticket_json = json_encode($sMsgArray,JSON_UNESCAPED_UNICODE);
            $row->save();
        }else{
            $insert = [
                'SuiteId' => $sMsgArray['SuiteId'],
                'suite_ticket' => $sMsgArray['SuiteTicket'],
                'ticket_time' =>  date('Y-m-d H:i:s'),
                'ticket_json' => json_encode($sMsgArray,JSON_UNESCAPED_UNICODE),
            ];
            CorpModel::create($insert);
        }
    }

    //永久授权逻辑处理
    public static function get_permanent_code($receiveid,$token,$encodingAesKey,$postStr)
    {
        $sMsg = '';
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $postStr, $sMsg);
        log_print('解密后的数据');
        log_print($sMsg);
        $sMsgArray = Xml2Array($sMsg);
        log_print('解密后转为数组');
        log_print($sMsgArray);
        //收到 AuthCode
        if(!empty($sMsgArray['InfoType']) && $sMsgArray['InfoType'] == 'reset_permanent_code'){
            $row = CorpModel::where("")->find();
            $suite_access_token = WorkModel::get_suite_token($row['suite_ticket']);
            WorkModel::get_permanent_code($suite_access_token,$sMsgArray['AuthCode'],$receiveid);
        }
        if(!empty($sMsgArray['InfoType']) && $sMsgArray['InfoType'] == 'create_auth'){
            $row = CorpModel::where("")->find();
            $suite_access_token = WorkModel::get_suite_token($row['suite_ticket']);
            WorkModel::get_permanent_code($suite_access_token,$sMsgArray['AuthCode'],$receiveid);
        }
        if($errCode === 0){
            log_print('解密内容');
            log_print($sMsg);
            return 'success';
        }else{
            log_print('回调失败33333');
            log_print("ERR: " . $errCode);
            return '';
        }
    }

}
